package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IMerchantService;

import javax.annotation.Resource;

/**
 * 商家Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-04
 */
@Service
public class MerchantServiceImpl implements IMerchantService {
    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private MerchantTypeMapper merchantTypeMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private FileSystemMapper fileSystemMapper;

    @Autowired
    private GoodsMapper goodsMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询商家
     *
     * @param id 商家主键
     * @return 商家
     */
    @Override
    public Merchant selectMerchantById(Long id) {
        Merchant merchant = merchantMapper.selectMerchantById(id);
        Category category = categoryMapper.selectCategoryByMerchantId(id);
        category.setChildren(categoryMapper.selectCategoryListByMerchantId(id));
        merchant.setCategoryList(category);
        if (merchant.getPic() != null) {
            merchant.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(merchant.getPic())));
        }
        if (merchant.getLogo() != null) {
            merchant.setLogoFile(fileSystemMapper.selectFileSystemById(Long.valueOf(merchant.getLogo())));
        }
        if (merchant.getEnvironmentPic() != null) {
            merchant.setEnvironmentPicFile(new ArrayList<>());
            String[] split = merchant.getEnvironmentPic().split(",");
            for (int i = 0; i < split.length; i++) {
                merchant.getEnvironmentPicFile().add(fileSystemMapper.selectFileSystemById(Long.valueOf(split[i])));
            }
        }
        return merchant;
    }

    /**
     * 查询商家列表
     *
     * @param merchant 商家
     * @return 商家
     */
    @Override
    public List<Merchant> selectMerchantList(Merchant merchant) {
        List<Merchant> merchants = merchantMapper.selectMerchantList(merchant);
        merchants.forEach(m -> {
            m.setFirstLevel(categoryMapper.selectFirstLevelById(m.getId()));
            m.setSecondLevel(categoryMapper.selectSecondLevelById(m.getId()));
            if (m.getPic() != null) {
                m.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(m.getPic())));
            }
            if (m.getLogo() != null) {
                m.setLogoFile(fileSystemMapper.selectFileSystemById(Long.valueOf(m.getLogo())));
            }
            if (m.getEnvironmentPic() != null) {
                m.setEnvironmentPicFile(new ArrayList<>());
                String[] split = m.getEnvironmentPic().split(",");
                for (int i = 0; i < split.length; i++) {
                    m.getEnvironmentPicFile().add(fileSystemMapper.selectFileSystemById(Long.valueOf(split[i])));
                }
            }
        });
        return merchants;
    }

    /**
     * 新增商家
     *
     * @param merchant 商家
     * @return 结果
     */
    @Override
    public int insertMerchant(Merchant merchant) {
        merchant.setCreateTime(DateUtils.getNowDate());


        if (merchant.getEnvironmentPicFile() != null) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < merchant.getEnvironmentPicFile().size(); i++) {
                if (merchant.getEnvironmentPicFile().get(i)!=null){
                    stringBuilder.append(merchant.getEnvironmentPicFile().get(i).getId());
                    if (i != merchant.getEnvironmentPicFile().size() - 1) {
                        stringBuilder.append(",");
                    }
                }

            }
            merchant.setEnvironmentPic(stringBuilder.toString());
        }
        if (merchant.getPicFile() != null){
            merchant.setPic(merchant.getPicFile().getId().toString());
        }
        if (merchant.getLogoFile() != null){
            merchant.setLogo(merchant.getLogoFile().getId().toString());
        }
        int j = merchantMapper.insertMerchant(merchant);
        if (merchant.getCategoryList() != null) {
            MerchantType merchantType = new MerchantType();
            merchantType.setMerchantId(merchant.getId());
            merchantType.setTypeId(merchant.getCategoryList().getId());
            merchantType.setParentId(0L);
            merchantTypeMapper.insertMerchantType(merchantType);
            for (Category category : merchant.getCategoryList().getChildren()) {
                merchantType.setMerchantId(merchant.getId());
                merchantType.setTypeId(category.getId());
                merchantType.setParentId(category.getParentId());
                merchantTypeMapper.insertMerchantType(merchantType);
            }
        }

        createUserAndBindMerchant(merchant, merchant);
        return j;
    }

    /**
     * 修改商家
     *
     * @param merchant 商家
     * @return 结果
     */
    @Override
    public int updateMerchant(Merchant merchant) {
        merchant.setUpdateTime(DateUtils.getNowDate());

        merchantTypeMapper.deleteMerchantTypeByMerchantId(merchant.getId());

        if (merchant.getCategoryList() != null) {
            MerchantType merchantType = new MerchantType();
            merchantType.setMerchantId(merchant.getId());
            merchantType.setTypeId(merchant.getCategoryList().getId());
            merchantType.setParentId(0L);
            merchantTypeMapper.insertMerchantType(merchantType);
            for (Category category : merchant.getCategoryList().getChildren()) {
                merchantType.setMerchantId(merchant.getId());
                merchantType.setTypeId(category.getId());
                merchantType.setParentId(category.getParentId());
                merchantTypeMapper.insertMerchantType(merchantType);
            }

        }

        if (merchant.getEnvironmentPicFile() != null) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < merchant.getEnvironmentPicFile().size(); i++) {
                if (merchant.getEnvironmentPicFile().get(i)!=null){
                    stringBuilder.append(merchant.getEnvironmentPicFile().get(i).getId());
                    if (i != merchant.getEnvironmentPicFile().size() - 1) {
                        stringBuilder.append(",");
                    }
                }
            }
            merchant.setEnvironmentPic(stringBuilder.toString());
        }
        if (merchant.getPicFile() != null){
            merchant.setPic(merchant.getPicFile().getId().toString());
        }
        if (merchant.getLogoFile() != null){
            merchant.setLogo(merchant.getLogoFile().getId().toString());
        }
        return merchantMapper.updateMerchant(merchant);
    }

    /**
     * 批量删除商家
     *
     * @param ids 需要删除的商家主键
     * @return 结果
     */
    @Override
    public int deleteMerchantByIds(Long[] ids) {
        return merchantMapper.deleteMerchantByIds(ids);
    }

    /**
     * 删除商家信息
     *
     * @param id 商家主键
     * @return 结果
     */
    @Override
    public int deleteMerchantById(Long id) {
        return merchantMapper.deleteMerchantById(id);
    }

    @Override
    public List<Merchant> selectMerchantApiList(Merchant merchant) {
        List<Merchant> merchants = merchantMapper.selectMerchantApiList(merchant);
        merchants.forEach(m -> {
            if (m.getLogo() != null) {
                m.setLogoFile(fileSystemMapper.selectFileSystemById(Long.valueOf(m.getLogo())));
            }
            List<Goods> goods = goodsMapper.selectGoodsListByMerchantId(m.getId());
            goods.forEach(goods1 -> {
                goods1.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(goods1.getPic())));
            });
            m.setGoods(goods);
        });
        return merchants;
    }

    @Override
    public Map<String, Object> goodsById(Long id) {
        Map<String, Object> map = new HashMap<>();
        Goods goods = goodsMapper.selectGoodsById(id);
        goods.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(goods.getPic())));
        Merchant merchant = merchantMapper.selectMerchantById(goods.getMerchantId());
        if (merchant.getPic() != null) {
            merchant.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(merchant.getPic())));
        }
        if (merchant.getLogo() != null) {
            merchant.setLogoFile(fileSystemMapper.selectFileSystemById(Long.valueOf(merchant.getLogo())));
        }
        if (merchant.getEnvironmentPic() != null) {
            merchant.setEnvironmentPicFile(new ArrayList<>());
            String[] split = merchant.getEnvironmentPic().split(",");
            for (int i = 0; i < split.length; i++) {
                merchant.getEnvironmentPicFile().add(fileSystemMapper.selectFileSystemById(Long.valueOf(split[i])));
            }
        }
        List<Goods> goodsList = goodsMapper.selectGoodsListByNotId(goods);
        goodsList.forEach(goods1 -> {
            goods1.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(goods1.getPic())));
        });
        map.put("goods", goods);
        map.put("merchant", merchant);
        map.put("goodsListNot", goodsList);
        return map;
    }

    @Override
    public List<Goods> selectGoodsListByMerchantId(Goods id) {
        List<Goods> goods = goodsMapper.selectGoodsListAllByMerchantId(id);
        goods.forEach(goods1 -> {
            if (goods1.getPic() != null) {
                goods1.setPicFile(fileSystemMapper.selectFileSystemById(Long.valueOf(goods1.getPic())));
            }
        });
        return goods;
    }

    @Override
    public int addMerchantUser(Merchant merchant) {
        if (merchant == null) {
            throw new IllegalArgumentException("商户信息不能为空");
        }

        if (merchant.getId() == null) {
            throw new IllegalArgumentException("商户ID不能为空");
        }

        if (merchant.getPassword() == null || merchant.getPassword().isEmpty()) {
            throw new IllegalArgumentException("商户密码不能为空");
        }

        Merchant m = merchantMapper.selectMerchantById(merchant.getId());
        if (m == null) {
            throw new RuntimeException("商户不存在");
        }

        if (m.getUserId() == null) {
            return createUserAndBindMerchant(merchant, m);
        } else {
            return updateUserPassword(m.getUserId(), merchant.getPassword());
        }
    }

    private int createUserAndBindMerchant(Merchant merchant, Merchant m) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(m.getPhone());
        sysUser.setNickName(m.getName());
        sysUser.setPhonenumber(m.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword(merchant.getPassword()));
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setMerchantId(m.getId());
        sysUserMapper.insertUser(sysUser);
        List<SysUserRole> userRoleList  = new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(999L);

        userRoleList.add(sysUserRole);
        sysUserRoleMapper.batchUserRole(userRoleList);

        m.setUserId(sysUser.getUserId());
        return merchantMapper.updateMerchant(m);
    }

    private int updateUserPassword(Long userId, String password) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        return sysUserMapper.updateUser(sysUser);
    }



}

